import store from 'yields-store'
import decodeJWT from 'jwt-decode'
import { error as err, success } from '../ui-components'
import cookie from 'component-cookie'

let token = {}
let base = {}

getToken()
decodeToken()

export
function getToken() {
  if (window.global_params && window.global_params.temporaryToken) {
    token['X-Temporary-Token'] = window.global_params.temporaryToken
  }

  if (!Object.keys(token).length) {
		token['X-Access-Token'] = cookie('X-Access-Token')
		token['X-Refresh-Token'] = cookie('X-Refresh-Token')
  }
  return token
}

function decodeToken() {
  if (token['X-Access-Token']) {
    base = {
      ...base,
      ...decodeJWT(token['X-Access-Token'])
    }
  }
}

export
function setToken(_token) {
	token['X-Access-Token'] = _token['accessToken'];
	token['X-Refresh-Token'] = _token['refreshToken'];
}

export
function checkStatus(response) {
	if (response.status >= 200 && response.status < 300) {
		return response
	} else {
		var error = new Error(response.statusText)
			error.response = response
			throw error
	}
}

export
function check(res) {
  const code = '' + res.code
  if (/^202\d+$/.exec(code)) {
    err(res.msg)
    throw new Error(res.msg)
  }

	if (!/^20\d+$/.exec(code)) {
		let error = new Error(res.msg)
		error.response = res
		throw error
	}
  
  return res
}

export
function checkCallback(response, option, data) {
  // body...
  const {
    failed,
    success,
  } = option;
  if (!(response.status >= 200 && response.status < 300)) {
    const error = new Error(response.statusText)
    error.response = response
    failed && failed(response);
    throw error;
  } else {
    const resJson = response.json();
    return resJson.then(res => {
      const code = '' + res.code;
      if (/^202\d+$/.exec(code)) {
        err(res.msg);
        failed && failed(res);
        throw new Error(res.msg)
      }else if (!/^20\d+$/.exec(code)) {
        let error = new Error(res.msg);
        error.res = res;
        failed && failed(res);
        throw error;
      }else {
        success && success(res.data);
        return res.data;
      }
    });
    
  }
}

export
function parseJSON(response) {
	return response.json()
}

export 
function data(res) {
	return res.data
}

export 
const Json = {
	'Accept': 'application/json',
	'Content-Type': 'application/json'
}

export 
const config = {
  'pragma': 'no-cache',
  'Cache-Control': 'no-cache,no-store',
  'Expires': -1,
	...Json,
  ...token,
}

export
const get = {
	method: 'get'
}

export
const post = {
	method: 'post'
}

export
const del = {
	method: 'delete'
}

export 
const put = {
  method: 'put',
}

let getJson = {
	...get,
	headers: {
		...config
	}
}

let postJson = {
	...post,
	headers: {
		...config
	}
}

let delJson = {
	...del,
	headers: {
		...config
	}
}

let putJson = {
	...put,
	headers: {
		...config
	}
}

export {
  delJson,
  getJson,
  putJson,
  postJson,
};

export 
const body = json => ({ body: JSON.stringify(json) })

export const u = {
	...base
}

export const updateToken = (_token) => {
  setToken(_token);
  delJson = {
    ...delJson,
    headers: {
      ...config,
      ...token,
    },
  };
  getJson = {
    ...getJson,
    headers: {
      ...config,
      ...token,
    },
  };
  postJson = {
    ...postJson,
    headers: {
      ...config,
      ...token,
    },
  };
  putJson = {
    ...putJson,
    headers: {
      ...config,
      ...token,
    },
  };
};
